package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.OrderDetail;
import com.itheima.entity.Orders;
import com.itheima.entity.ShoppingCart;
import com.itheima.dto.OrdersDto;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrderService;
import com.itheima.service.ShoppingCartService;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders, HttpServletResponse response, HttpServletRequest request) throws IOException {
        log.info("订单数据：{}", orders);
        Orders orders1 = orderService.submit(orders);
        request.getSession().setAttribute("orders", orders1);
        return R.success("下单成功");
    }

    /**
     * 付款成功 修改订单状态
     *
     * @param request
     * @return
     */
    @PutMapping("/updateStatus")
    public R<String> updateStatus(HttpServletRequest request) {
        Orders orders = (Orders) request.getSession().getAttribute("orders");
        orders.setStatus(2);
        orderService.updateById(orders);
        return R.success("支付成功");

    }

    /**
     * 用户端分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize) {
        orderService.updateStatus();
        //获取当前用户id
        Long userID = BaseContext.getCurrentId();
        //查询基础订单信息
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getUserId, userID);
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, ordersLambdaQueryWrapper);
        //克隆分页信息
        Page<OrdersDto> ordersDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, ordersDtoPage, "records");
        //克隆基础信息已经订单详情
        List<Orders> orders = pageInfo.getRecords();
        List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders orders1 : orders) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders1, ordersDto);
            ordersDto.setUserName(userService.getById(userID).getName());
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orders1.getId());
            List<OrderDetail> list = orderDetailService.list(orderDetailLambdaQueryWrapper);
            ordersDto.setOrderDetails(list);

            ordersDtos.add(ordersDto);
        }
        ordersDtoPage.setRecords(ordersDtos);
        return R.success(ordersDtoPage);
    }

    /**
     * 后台分页查询
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime) {
        log.info(beginTime);
        log.info(endTime);
        //设置时间格式
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据订单号模糊查询
        ordersLambdaQueryWrapper.like(number != null, Orders::getNumber, number);
        if (StringUtils.isNotEmpty(beginTime)) {
            //大于开始时间
            ordersLambdaQueryWrapper.ge(Orders::getOrderTime, LocalDateTime.parse(beginTime, fmt));
        }
            //小于结束时间
        if (StringUtils.isNotEmpty(endTime)) {
            ordersLambdaQueryWrapper.le(Orders::getOrderTime, LocalDateTime.parse(endTime, fmt));
        }
        ordersLambdaQueryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, ordersLambdaQueryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 后台修改订单状态
     *
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> updateStatus(@RequestBody Orders orders) {
        orderService.updateById(orders);
        return R.success("修改成功");

    }

    /**
     * 再来一单
     *
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders) {
        //先清空购物车
        log.info(orders.toString());
        shoppingCartService.remove(new LambdaQueryWrapper<>());
        //根据订单id查询订单详情
        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetails = orderDetailService.list(lambdaQueryWrapper);
        //将订单详情数据克隆到购物车数据（id除外）
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            //设置当前用户id
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCarts.add(shoppingCart);
        }
        //添加到购物车表
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("成功");
    }
}